from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import DatabaseError
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from .models import User
from django.http import JsonResponse, HttpResponseForbidden
from utils.response_code import RETCODE


# 用户注册
class RegisterView(View):
    def get(self, request):
        """提供用户注册页面"""
        return render(request, 'register.html')

    def post(self, request):
        # 1.接收请求参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get("allow")  # 是否同意协议

        # 判断用户是否勾选协议
        if allow != 'on':
            return HttpResponseForbidden("请勾选用户协议")

        # 保存注册数据：是注册业务的核心
        try:
            # 注册成功的用户对象
            user = User.objects.create_user(username=username, mobile=mobile, password=password, )
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        login(request, user)  # 登入用户,实现状态保持

        # 响应登录结果:重定向到首页
        response = redirect(reverse('contents:index'))  # 使用命名空间反向解析
        # 为了实现在首页右上角展示用户信息,我们需要将用户名缓存到cookie中
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response


# 用户名重名的检测
class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


# 手机号重名检测
class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', "count": count})


# 用户登录
class LoginView(View):
    def get(self, request):
        return render(request, "login.html")

    def post(self, request):
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        # django框架 封装authenticate方法,自动从数据库中寻找用户
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '账号或密码错误'})

        # 登录成功后状态保持,把数据写入到session中(django自带方法)
        login(request, user)

        if remembered != 'on':
            request.session.set_expiry(0)  # 没有记住用户：浏览器会话结束就过期
        else:
            request.session.set_expiry(None)  # 记住用户：None表示两周后过期
        # 在settings.py中可以设置SESSION_COOKIE_AGE来配置全局的过期时间。默认是2周的时间

        next = request.GET.get('next')  # 取出登录后要进入的页面
        if next:
            response = redirect(next)  # 重定向到next
        else:
            response = redirect(reverse('contents:index'))

        # 注册时用户名写入到cookie，有效期14天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response  # 响应登录结果


# 用户登出
class LogoutView(View):
    """用户退出登录"""

    def get(self, request):
        # 清除状态保持信息
        logout(request)
        # 响应结果 重定向到首页
        response = redirect(reverse('contents:index'))
        # 删除cookie中的用户名
        response.delete_cookie('username')

        return response


# LoginRequiredMixin确保是登录状态
class UserInfoView(LoginRequiredMixin, View):
    """用户中心"""

    def get(self, request):
        """提供用户中心页面"""
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            "email": "12306@qq.com"
        }
        return render(request, 'user_center_info.html', context)
